package cn.huapu.power.energy.controller;

import cn.huapu.power.energy.bean.*;
import cn.huapu.power.energy.bean.bo.DateParameterBo;
import cn.huapu.power.energy.bean.vo.*;
import cn.huapu.power.energy.service.*;
import cn.huapu.power.energy.util.ObjectHelper;
import cn.huapu.power.energy.util.RoleUtil;
import cn.huapu.power.energy.vo.Grid;
import cn.huapu.power.energy.vo.Page;
import cn.huapu.power.energy.vo.Ret;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jiangzhengxiong
 * @title: LadderPriceController
 * @projectName energy
 * @description:  阶梯电价电费表及电能组成页面接口
 * @date 2019-5-2717:02
 */
@RestController
@RequestMapping("/lad")
public class LadderPriceController {

    private Log log = LogFactory.getLog(LadderPriceController.class);

    @Autowired
    private PowerfeesService poService;
    @Autowired
    private ClntpwrsourcetService clnService;
    @Autowired
    private ClntpowerpriceService clntprService;
    @Autowired
    private MnPowerfeesService mService;
    @Autowired
    private SysUserService sysUserService;
    
    /**
    * @Author jzx 
    * @Description  尖、峰、谷、平电费使用占比接口
    * @Date 17:13 2019-5-27
    * @Param [map] 
    * @return cn.huapu.power.energy.vo.Ret 
    **/
    @RequestMapping(value = "/ecectFessZb",method = RequestMethod.POST)
    public Ret pricePortion(@RequestBody DateParameterBo dateParameterBo, HttpSession session){
    	SysUser user = (SysUser)session.getAttribute("user");
        String username = user.getUsername();
        dateParameterBo.setName(username);
        PowerFessZBVo powerFessZB = poService.pricePortion(dateParameterBo);
        Ret r = new Ret();
        r.OK(powerFessZB);
        return r;
    }

    /**
    * @Author jzx
    * @Description //尖、峰、谷、平电量使用占比接口
    * @Date 9:51 2019-5-28
    * @Param [dateParameterBo, session]
    * @return cn.huapu.power.energy.vo.Ret
    **/
    @RequestMapping(value = "/electTityZb",method = RequestMethod.POST)
    public Ret electTityZb(@RequestBody DateParameterBo dateParameterBo, HttpSession session){
        PowerFessZBVo powerFessZB = clnService.getElectTityZb(dateParameterBo);
        Ret r = new Ret();
        r.OK(powerFessZB);
        return r;
    }






    /**
    * @Author jzx
    * @Description //最大需-容量电费对比
    * @Date 11:30 2019-6-11
    * @Param [da]
    * @return cn.huapu.power.energy.vo.Ret
    **/
    @RequestMapping(value = "/electCapa",method = RequestMethod.POST)
    public Ret electCapa(@RequestBody DateParameterBo da){
       List<MnPowerfees> list = mService.getElecCapa(da);
       Ret r = new Ret();
       r.OK(list);
       return r;
    }


    /**
    * @Author jzx
    * @Description //根据id与时间得到两个周期时间
    * @Date 11:28 2019-6-11
    * @Param [id, time]
    * @return java.util.Map<java.lang.String,java.lang.String>
    **/
   public Map<String,Object> getBackTime(int readTime,int cycle,LocalDate date){   
       
        //获取当前抄表时间     
        int year = date.getYear();
        int month= date.getMonthValue();             
        String datStre = year+"-"+month+"-"+readTime;
        //获取上一周期抄表时间
        int year1 = 0;
        int month1 = month-cycle;
        if(month1 <=0){
            month1 = month1+12;
            year1 = year-1;
        }else{
            year1 = year;
        }
        String date1 = year1+"-"+month1+"-"+readTime;
        Map<String,Object> map = new HashMap<>(2);
        map.put("date",datStre);
        map.put("date1",date1);
        map.put("localdate1", LocalDate.of(year1, month1, readTime));
        return map;
    }


    /**
    * @Author jzx
    * @Description //年、月电量分布
    * @Date 15:20 2019-6-5
    * @Param [da]
    * @return cn.huapu.power.energy.vo.Ret
    **/
    @RequestMapping(value = "/electDistr",method = RequestMethod.POST)
    public Ret electDistr(@RequestBody DateParameterBo da){
        Map<String, Object> map = clnService.getElectDistr(da);
        Ret r = new Ret();
        r.OK(map);
        return r;
    }


    /**
     * @Author jzx
     * @Description //周期电量分布图
     * @Date 15:55 2019-6-10
     * @Param [da]
     * @return cn.huapu.power.energy.vo.Ret
     **/
    @RequestMapping(value = "/electCycle",method = RequestMethod.POST)
    public Ret electCycle(@RequestBody DateParameterBo da){
    	 Ret r = new Ret();
    	 //根据id获取抄表时间与抄表周期
        ClientpowerstVo clientpo = clnService.getReadTime(da);
        if(clientpo == null) {
        	return r;
        }       
        int readCycle = clientpo.getReadCycle();
        int readDay = clientpo.getReadTime();
        LocalDateTime last = clnService.getLastDate(da);
        LocalDate date  = last.toLocalDate();
        if(last == null) {
        	return r;
        }
        //获取两个周期时间
        if(readCycle>1) {
        	int adjuge = last.getMonthValue()/readCycle;
            if (adjuge * readCycle == 12) {
                date = LocalDate.of(date.getYear(), adjuge*readCycle, 1).plusMonths(1);
            } else {
                date = LocalDate.of(date.getYear(), adjuge*readCycle+1, 1);
            }
        }
        Map<String, Object> backTime = this.getBackTime(readDay,readCycle,date);
        List<ClntPowerVo> list = new ArrayList<>(3); 
        int v = 12/readCycle;
        for (int i = 0; i < v; i++) {
            ClntPowerVo clnt = clnService.getReadPower((String)backTime.get("date"), (String)backTime.get("date1"),da.getId());
            if(clnt != null) {
	            clnt.setDateOne((String)backTime.get("date"));
	            clnt.setDateTwo((String)backTime.get("date1"));
	            backTime = this.getBackTime(readDay,readCycle, (LocalDate)backTime.get("localdate1"));
	            list.add(clnt);
            }
            else {
            	//break;
            }
        }
        list.remove(null);
        Map<Integer, List<ClntPowerVo>> collect = list.stream().collect(Collectors.groupingBy(e -> e.getYear()));
       
        r.OK(collect);
        return r;
    }

//    public Map<String, Object> getDateAndClntMap(String id, Map<String, Object> backTime, List<ClntPowerVo> list) {
//        ClntPowerVo clnt = clnService.getReadPower((String)backTime.get("date"), (String)backTime.get("date1"),id);
//        backTime = this.getBackTime(id, (String)backTime.get("date1"));
//        list.add(clnt);
//        return backTime;
//    }

    /**
    * @Author jzx
    * @Description 年、月电量采集图
    * @Date 14:10 2019-5-28
    * @Param
    * @return
    **/
    @RequestMapping(value = "/electCollection",method = RequestMethod.POST)
    public Ret electCollection(@RequestBody DateParameterBo da){
        List<EcectCollectionVo> ecectCollectionVos = clnService.electCollection(da);
        Ret r = new Ret();
        r.OK(ecectCollectionVos);
        return r;
    }

    /**
    * @Author jzx
    * @Description //电费分布及走势
    * @Date 17:17 2019-6-27
    * @Param [da]
    * @return cn.huapu.power.energy.vo.Ret
    **/
    @RequestMapping(value = "/electTrend",method = RequestMethod.POST)
    public Ret electTrend(@RequestBody DateParameterBo da){
        List<Powerfees> powerfees = poService.getElectTrend(da);
        Ret r = new Ret();
        r.OK(powerfees);
        return r;
    }


    /**
    * @Author jzx
    * @Description //周期电量采集
    * @Date 17:20 2019-6-17
    * @Param [da]
    * @return cn.huapu.power.energy.vo.Ret
    **/
    @RequestMapping(value = "/electCollectionCycle",method = RequestMethod.POST)
    public Ret electCollectionCycle(@RequestBody DateParameterBo da){
        List<ClntPowerVo> clnt = clnService.getDateAndClntcj(da.getDateOne(),da.getDateTwo(),da.getId());
        Ret r = new Ret();
        r.OK(clnt);
        return r;
    }




    /**
    * @Author jzx
    * @Description //周期电费分布及走势
    * @Date 15:45 2019-6-20
    * @Param [da]
    * @return cn.huapu.power.energy.vo.Ret
    **/
    @RequestMapping(value = "/cycleFess",method = RequestMethod.POST)
    public Ret cycleFess(@RequestBody DateParameterBo da){
        List<ClntPowerVo> clnts = clnService.getCycleFess(da);
        Ret r = new Ret();
        r.OK(clnts);
        return r;
    }

    /**
     * @Author jzx
     * @Description //周期电费占比
     * @Date 15:47 2019-7-1
     * @Param [da]
     * @return cn.huapu.power.energy.vo.Ret
     **/
    @RequestMapping(value = "/electFessZB",method = RequestMethod.POST)
    public Ret electFessZB(@RequestBody DateParameterBo da){
        List<ClntPowerVo> clnts = clnService.getElectFessZB(da);
        Ret r = new Ret();
        r.OK(clnts);
        return r;
    }

    /**
    * @Author jzx
    * @Description 电量电费表格接口
    * @Date 9:58 2019-5-29
    * @Param [session]
    * @return cn.huapu.power.energy.vo.Ret
    **/
    @RequestMapping(value = "/electForm",method = RequestMethod.POST)
    public Ret electForm(@RequestBody DateParameterBo da){
        List<ElectFormVo> electForms = poService.getElectform(da);
        Ret r = new Ret();
        r.OK(electForms);
        return r;
    }



    /**
    * @Author jzx
    * @Description 电价表格
    * @Date 14:34 2019-5-29
    * @Param [page, session]
    * @return cn.huapu.power.energy.vo.Ret
    **/
    @RequestMapping(value = "/electPrice",method = RequestMethod.POST)
    public Ret electPrice(@RequestBody DateParameterBo da,HttpSession session){
        String[] split = da.getDateOne().split("-");
        String year = split[0];
        String month="";
        String day="";
        if(split.length>=2){
            month = split[1].replace("0","");
        }
        if(split.length>=3){
            day = split[2].replace("0","");
        }


        String[] split1 = da.getDateTwo().split("-");
        String year1 = split1[0];
        String month1="";
        String day1="";
        if(split1.length>=2){
            month1 = split1[1].replace("0","");
        }
        if(split1.length>=3){
            day1 = split1[2].replace("0","");
        }      
        boolean b = judegeAdmin(session);
        Map<String,Object> map = new HashMap<>(15);
        Page page = new Page();
        page.setRows(da.getRows());
        page.setPage(da.getPage());
        map.put("page",page);
        map.put("year",year);
        map.put("month",month);
        map.put("day",day);
        map.put("year1",year1);
        map.put("month1",month1);
        map.put("day1",day1);
        Grid<Clntpowerprice> userDataGrid = new Grid<>();
        List<Clntpowerprice> cls;
        if(b){ //超级管理员，显示所有用户
            cls = clntprService.getAllElectPricePage(map);//获取所有用户电价
            userDataGrid.setTotal(page.getTotalCount());
            userDataGrid.setRows(cls);
        }else{
            map.put("id",da.getId());
            cls = clntprService.getElectPricePage(map);//获取当前用户电价
            userDataGrid.setTotal(page.getTotalCount());
            userDataGrid.setRows(cls);
        }
        Ret r = new Ret();
        r.OK(userDataGrid);
        return r;
    }

    /**
    * @Author jzx
    * @Description 判断是否是超级管理员
    * @Date 13:46 2019-5-29
    * @Param [session]
    * @return void
    **/
    private boolean judegeAdmin(HttpSession session) {
    	SysUser user = (SysUser)session.getAttribute("user");
    	if(user != null) {
    		List<Integer> list = sysUserService.getRoleId(user.getPkid());
    		if(!list.isEmpty()) {
    			for (Integer r : list) {
					if(r.intValue() == RoleUtil.ROLE_ADMIN) {
						return true;
					}
				}
    		}
    	}    	
        return false;
    }

}
